import 'package:flutter/material.dart';
import '../theme/theme.dart';
import 'side_menu_item.dart';

/// 左侧菜单栏组件
class SideMenuBar extends StatelessWidget {
  final String? title;
  final bool? isCollapsed;
  final List<SideMenuItem>? menuItems;
  final String currentPage;
  final Function(String) onMenuItemSelected;

  // 缓存路径映射，避免重复计算
  final Map<String, String> _pathCache = {};

  SideMenuBar({
    super.key, 
    this.title, 
    this.isCollapsed, 
    this.menuItems,
    required this.currentPage,
    required this.onMenuItemSelected,
  });

  @override
  Widget build(BuildContext context) {
    HTheme theme = HTheme.of(context);
    // 构建左侧导航栏
    return Container(
      color: theme.colors.sidebar,
      child: Column(
        children: [
          // Logo和标题区域
          _buildHeaderTitle(theme),
          
          // 菜单区域
          _buildMenuContent(),
        ],
      ),
    );
  }

  Expanded _buildMenuContent() {
    return Expanded(
      child: ListView.builder(
        padding: EdgeInsets.zero,
        itemCount: menuItems?.length ?? 0,
        itemBuilder: (context, index) {
          final item = menuItems?[index];
          
          if (item == null) return const SizedBox.shrink();
          
          // 如果是有子菜单的父菜单项，则使用ExpansionTile
          if (item.hasChildren) {
            return _buildMenuItemWithChildren(context, item, 0, null);
          }
          
          // 如果route为null，则使用一个空字符串作为默认值
          final routeName = item.route;
          return _buildMenuItem(context, item.title, item.icon, routeName);
        },
      ),
    );
  }

  Container _buildHeaderTitle(HTheme theme) {
    return Container(
      height: 60,
      alignment: Alignment.center,
      decoration: BoxDecoration(
        color: theme.colors.sidebarHeader,
        border: Border(
          bottom: BorderSide(color: theme.colors.divider),
        ),
      ),
      child: isCollapsed ?? false
          ? const Text(
              'Miaoyi',
              style: TextStyle(
                color: Colors.white,
                fontSize: 21,
                fontWeight: FontWeight.bold,
              ),
            )
          : Text(
              title ?? 'Miaoyi Admin',
              style: const TextStyle(
                color: Colors.white,
                fontSize: 20,
                fontWeight: FontWeight.bold,
              ),
            ),
    );
  }
  
  /// 构建带有子菜单的菜单项 (统一处理所有层级)
  Widget _buildMenuItemWithChildren(
    BuildContext context, 
    SideMenuItem item, 
    int level, 
    String? parentPath
  ) {
    final theme = HTheme.of(context);
    // 计算左侧缩进
    final double leftPadding = level == 0 ? 0 : 16.0 + (level * 14.0);
    // 计算当前菜单项的完整路径
    final String itemFullPath = _getFullPath(item, parentPath);
    // 获取标准化路径用于比较选中状态
    final String normalizedPath = itemFullPath.startsWith('/') 
        ? itemFullPath.substring(1) 
        : itemFullPath;
    // 判断当前菜单项是否被选中
    final bool isSelected = currentPage == normalizedPath;
    // 设置背景色，一级菜单使用默认色，子菜单使用深色
    Color bgColor = level == 0 ? Colors.transparent : const Color(0xFF1F2D3D);
    // 如果当前项被选中，使用选中背景色
    if (isSelected) {
      bgColor = level == 0 ? const Color(0xFF293846) : theme.colors.primary;
    }
    
    return Theme(
      // 使用自定义主题，调整ExpansionTile的样式
      data: Theme.of(context).copyWith(
        dividerColor: Colors.transparent,
        colorScheme: Theme.of(context).colorScheme.copyWith(
          background: bgColor,
        ),
      ),
      child: ExpansionTile(
        collapsedIconColor: Colors.white60,
        iconColor: Colors.white,
        backgroundColor: bgColor,
        collapsedBackgroundColor: bgColor,
        tilePadding: EdgeInsets.only(left: level == 0 ? 20 : leftPadding, right: 10.0),
        title: Row(
          children: [
            if (level == 0) 
              Icon(
                item.icon,
                color: isSelected ? Colors.white : Colors.white60,
                size: 16,
              ),
            if (!(isCollapsed ?? false) || level > 0) ...[
              if (level == 0) const SizedBox(width: 12),
              Text(
                item.title,
                style: TextStyle(
                  color: isSelected ? Colors.white : (level == 0 ? Colors.white : Colors.grey.shade400),
                  fontSize: 14,
                ),
              ),
            ],
          ],
        ),
        children: item.children?.map((child) {
          // 递归处理嵌套菜单
          if (child.hasChildren) {
            return _buildMenuItemWithChildren(
              context, 
              child, 
              level + 1, 
              itemFullPath
            );
          }
          
          // 构建完整的路径
          final String fullPath = _getFullPath(child, itemFullPath);
          
          // 创建带有额外缩进的菜单项
          return _buildSubMenuItem(
            context, 
            child.title, 
            child.route,
            fullPath: fullPath,
            additionalPadding: level * 14.0,
          );
        }).toList() ?? [],
      ),
    );
  }
  
  /// 获取菜单项的完整路径（使用缓存提高性能）
  String _getFullPath(SideMenuItem item, String? parentPath) {
    // 生成缓存键
    final String cacheKey = '${parentPath ?? ""}:${item.route}';
    
    // 如果已缓存，直接返回
    if (_pathCache.containsKey(cacheKey)) {
      return _pathCache[cacheKey]!;
    }
    
    // 计算完整路径
    String fullPath;
    if (parentPath == null || parentPath.isEmpty) {
      fullPath = item.route;
    } else {
      fullPath = '$parentPath/${item.route}';
    }
    
    // 标准化路径
    fullPath = _normalizeFullPath(fullPath);
    
    // 存入缓存
    _pathCache[cacheKey] = fullPath;
    
    return fullPath;
  }
  
  /// 构建二级菜单项，添加缩进和不同的背景色
  Widget _buildSubMenuItem(
    BuildContext context, 
    String title, 
    String routeName, 
    {double additionalPadding = 0.0, String? fullPath}
  ) {
    final theme = HTheme.of(context);
    // 使用完整路径来判断是否选中，移除开头的斜杠再比较
    final String normalizedPath = fullPath?.startsWith('/') == true 
        ? fullPath!.substring(1) 
        : fullPath ?? routeName;
    
    // 检查当前路径是否匹配，支持完整路径和最后部分的匹配
    bool isSelected = false;
    if (currentPage == normalizedPath) {
      isSelected = true;
    } else if (normalizedPath.contains('/')) {
      // 尝试匹配路径的最后一部分（向后兼容）
      final List<String> parts = normalizedPath.split('/');
      if (parts.isNotEmpty && currentPage == parts.last) {
        isSelected = true;
      }
    }
    
    // 二级菜单使用稍微不同的背景色
    final Color bgColor = isSelected ? theme.colors.primary : const Color(0xFF1F2D3D);
    final Color hoverColor = isSelected ? bgColor : const Color.fromARGB(255, 55, 74, 91);
    final Color textColor = isSelected ? Colors.white : Colors.grey.shade400;

    return Material(
      color: bgColor,
      child: InkWell(
        hoverColor: hoverColor,
        onTap: () {
          onMenuItemSelected(fullPath ?? routeName);
        },
        child: Container(
          padding: EdgeInsets.only(
            left: 30.0 + additionalPadding,
            right: 10,
            top: 12,
            bottom: 12,
          ),
          child: Row(
            children: [
              if (!(isCollapsed ?? false)) ...[
                const SizedBox(width: 6),
                Expanded(
                  child: Text(
                    title,
                    style: TextStyle(
                      color: textColor,
                      fontSize: 14,
                    ),
                  ),
                ),
              ],
            ],
          ),
        ),
      ),
    );
  }
  
  /// 标准化完整路径，去除冗余斜杠并确保格式正确
  String _normalizeFullPath(String path) {
    // 移除连续的斜杠
    while (path.contains('//')) {
      path = path.replaceAll('//', '/');
    }
    
    // 确保开头有斜杠
    if (!path.startsWith('/')) {
      path = '/$path';
    }
    
    return path;
  }
  
  /// 构建菜单项
  Widget _buildMenuItem(BuildContext context, String? title, IconData? icon, String routeName) {
    final theme = HTheme.of(context);
    
    // 检查当前路径是否匹配，支持路径的完整匹配和最后部分匹配
    bool isSelected = currentPage == routeName;
    if (!isSelected && routeName.contains('/')) {
      // 尝试匹配路径的最后一部分（向后兼容）
      final List<String> parts = routeName.split('/');
      if (parts.isNotEmpty && currentPage == parts.last) {
        isSelected = true;
      }
    }
    
    final Color bgColor = isSelected ? const Color(0xFF293846) : Colors.transparent;
    final Color textColor = isSelected ? Colors.white : Colors.grey.shade400;
    
    return Material(
      color: bgColor,
      child: InkWell(
        hoverColor: const Color(0xFF1F2D3D), // 一级菜单的悬停颜色
        onTap: () {
          onMenuItemSelected(routeName);
        },
        child: Container(
          padding: const EdgeInsets.symmetric(
            horizontal: 20,
            vertical: 12,
          ),
          child: Row(
            children: [
              Icon(icon ?? Icons.circle, color: textColor, size: 16),
              if (!(isCollapsed ?? false)) ...[
                const SizedBox(width: 12),
                Expanded(
                  child: Text(
                    title ?? '',
                    style: TextStyle(
                      color: textColor,
                      fontSize: 14,
                    ),
                  ),
                ),
              ],
            ],
          ),
        ),
      ),
    );
  }
}